<?php
/**
 * Medical Centers List - Block Part
 *
 * @author Xavier VILAIN
 * @package Nawa
 * @subpackage MedicalCenters
 */

use Nawa\MedicalCenter;
use Nawa\MedicalStudy;
use Nawa\Customer;
use Doctrine\DBAL\Connection;
use Fox\Html\Block;

$xview = Xview::instance();
$msid = $xview->val('msid');
$block = $xview->component('medicalstudies','medicalcenters',array('msid' => $msid));
$gridId = 'gMedicalCentersPartners';
$grid = $block->item($gridId);
$ajax = Xview::instance()->val('xvtrs',false);
if($ajax)
{
	$uniqueData = null;
	$data = $grid->get();
	if(is_array($data[$gridId]))
	{
		foreach($data[$gridId] as $key => $line)
		{
			if(empty($line['mcid'])) {
				continue;
			}
			$uniqueData[$line['mcid']] = $line;
		}
	}
	$codes = Xview::instance()->val('codes');
	if(is_array($codes))
	{
		$ms =  $xview->component('medicalstudies','medicalstudy',array('allowVoid' => true));
		$finder = new MedicalCenter();
		$res = $finder->find(new Fox\Dao\SqlFragment('mcid IN (?)',
			array($codes),
			array(Connection::PARAM_INT_ARRAY)));
		foreach($res as $item)
		{
			$data = $item->getData();
			$data['mcid'] = $item->getId();
			$data['role'] = MedicalStudy::ROLE_MEDICAL_CENTERS;
			// Auto Save Data to the MS-MC
			//@TODO build a customizing point here
			if($ms->exists()) {
				try {
					$center = new MedicalStudy\MedicalCenter();
					$center->setFields($data);
					$ms->addToMedicalCentersPartners($center);
					$ms->prepareUpdate(MedicalStudy::CHANGE_ADD_MEDICAL_CENTERS);
					$ms->update();
				} catch (Fox\Object\Exception\Save $e) {
					\Fox\Message::Error($e);
				}
			}
			$uniqueData[$item->getId()] = $data;
		}
	}
	$grid->initialize($uniqueData,true);
	echo $grid->display();
}
else
{
	return $block;
}